package com.lcc.codehelper.factory;

import cn.hutool.core.date.DateTime;
import com.lcc.codehelper.config.TemplateConstant;
import com.lcc.codehelper.core.TableConfig;
import com.lcc.codehelper.entity.Table;
import com.lcc.codehelper.util.FileUtil;
import com.lcc.codehelper.parse.TableParse;
import com.lcc.codehelper.util.InitialCapacityUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import javax.annotation.Resource;
import java.io.File;
import java.util.*;

@Component
public class GenerateFactory {

    @Autowired
    private Configuration configuration;

    @Resource
    TableParse tableParse;

    @Resource
    TableConfig tableConfig;

    public void buildXml()  {
        generate(TemplateConstant.TEMPLATE_XML,tableConfig.getMapper()); }
    public void buildPO()  {
        generate(TemplateConstant.TEMPLATE_PO,tableConfig.getPo());
    }
    public void buildParam() { generate(TemplateConstant.TEMPLATE_PARAM,tableConfig.getParam()); }
    public void buildDTO()  {
        generate(TemplateConstant.TEMPLATE_DTO,tableConfig.getDto());
    }
    public void buildCounts()  {
        generate(TemplateConstant.TEMPLATE_COUNTS,tableConfig.getCounts());
    }

    public void buildService()  { generate(TemplateConstant.SERVICE,tableConfig.getService()); }
    public void getProvider()  {
        generate(TemplateConstant.Provider,tableConfig.getProvider());
    }
    public void getApi()  {
        generate(TemplateConstant.API,tableConfig.getApi());
    }
    public void buildServiceImpl()  {
        generate(TemplateConstant.SERVICE_IMPL,tableConfig.getServiceImpl());
    }
    public void buildMapper()  {
        generate(TemplateConstant.MAPPER,tableConfig.getMapper());
    }
    public void buildManager()  {
        generate(TemplateConstant.MANAGER,tableConfig.getManager());
    }
    public void getController()  {
        generate(TemplateConstant.CONTROLLER,tableConfig.getController());
    }

    Map<String,Object> map = new HashMap<>(InitialCapacityUtil.getInitialCapacity(15));
    public void build(){
        //初始化map
        init();

//      buildPO();
//      buildDTO();
//      buildParam();
//        if (tableConfig.getNeedStatistics()){
//            buildCounts();
//        }
//      buildMapper();
//      buildXml();
//      buildManager();
      buildService();
      buildServiceImpl();
//      getApi();
//      getProvider();
//      getController();
    }

    public void init(){
        map.put("provider",tableConfig.getProvider());
        map.put("api",tableConfig.getApi());
        map.put("manager",tableConfig.getManager());
        map.put("dto",tableConfig.getDto());
        map.put("param",tableConfig.getParam());
        map.put("po",tableConfig.getPo());
        map.put("service",tableConfig.getService());
        map.put("serviceImpl",tableConfig.getServiceImpl());
        map.put("mapper",tableConfig.getMapper());
        map.put("author",tableConfig.getAuthor());
        map.put("date",DateTime.now().toString("yyyy/MM/dd"));
        map.put("interfaceAddress",tableConfig.getInterfaceAddress());
        map.put("ifNeedStatistics",tableConfig.getNeedStatistics());
        map.put("counts",tableConfig.getCounts());
        map.put("ifSpiltByEnt",tableConfig.getSplitByEnt());
        map.put("extBean",tableConfig.getExtBean());
    }

    private String getFileName(String template,String tableAlias){
        //处理xml
        if(TemplateConstant.TEMPLATE_XML.equals(template)){
            return template.replace(TemplateConstant.ENTITY,tableAlias).replace("Xml","").replace("ftl","xml");
        }
        //处理countsDTO 不添加表名前缀
        if (TemplateConstant.TEMPLATE_COUNTS.equals(template)){
            return template.replace(TemplateConstant.ENTITY, "").replace("ftl",TemplateConstant.JAVA);
        }
        //普通的java文件
        return template.replace(TemplateConstant.ENTITY,tableAlias).replace("ftl",TemplateConstant.JAVA);
    }


    public void generate(String templateXml, String path){
        try {
            Template template = configuration.getTemplate(templateXml);
            Table table = tableParse.parseTable(tableConfig.getTable(),tableConfig.getSplitByEnt());
            map.put("table",table);
            String fileName = getFileName(templateXml,table.getAlias());
            String out = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
            String filePath = filePath(templateXml,path);
            FileUtil.writeFile(new File(filePath+ File.separator + fileName),out,
                    TemplateConstant.ENCODE);
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     *  项目文件路径
     * @param templateXml
     * @param path
     * @return
     */
    private String filePath(String templateXml,String path){
        StringBuilder stringBuilder = new StringBuilder();
        String projectDir = System.getProperty("user.dir");
        String pkgPath = path.replace(".", File.separator);
        String pkgDir =pkgDir(templateXml);
        String filePath = stringBuilder.append(projectDir).append(pkgDir).append(pkgPath).toString();
        return filePath;
    }

    /**
     * 包路径
     * @param templateXml
     * @return
     */
    private String pkgDir(String templateXml){
        if(TemplateConstant.TEMPLATE_XML.equals(templateXml)){
           return TemplateConstant.RESOURCE;
        }
        return TemplateConstant.PKG_PATH;
    }
}
